// pages/my/my.js

import {
  userDetail,
  userGetPhone,
  getQrCode,
  isPay
} from '../../../common/api/my'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: getApp().globalData.navBarHeight,
    statusBarHeight: getApp().globalData.statusBarHeight,
    bgHeight: 380,
    user: {},
    visible: false,
    codeUrl: '',
    visible2: false,
    codeUrl2: "../../../images/kefuCode.png",
    payCheck:false,
  },
  onPullDownRefresh: function () {
    console.log('下拉刷新');
    this.getUserDetail();
    this.getIsPay();
    // 在这里编写数据更新的逻辑
    setTimeout(() => {
      wx.stopPullDownRefresh(); // 数据更新完成后，调用该方法停止刷新
    }, 500);

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // let obj = wx.getStorageSync('userInfo') || {};
    this.getUserDetail();
    this.getIsPay();
    this.setData({
      bgHeight: this.data.statusBarHeight > 20 ? (this.data.statusBarHeight - 20) * 2 + 380 : 380,

    })
  },
  onShareAppMessage(e) {
    let user = wx.getStorageSync('userInfo');
    console.log(e);
    return {
      title: "杆赢天下，求胜未来。一元乐享好球杆，千万球友的选择",
      imageUrl: "../../../images/shareImg.jpg",
       path: "/pages/index/index?id=" + user.id
    }
  },
  goPage(page) {
    console.log(page.target.dataset.url)
    wx.navigateTo({
      url: page.target.dataset.url,
    })
  },
  onVisibleChange2(e) {
    this.setData({
      visible2: e.detail.visible,
    });
  },
  // 打开联系客服弹窗
  openVisible() {
    this.setData({
      visible2: true
    });
  },
  // ip定位
  getLocation() {
    let vm = this;
    return new Promise((res, jet) => {
      wx.request({
        url: 'https://apis.map.qq.com/ws/location/v1/ip?key=Q7SBZ-7DOW3-7IV3Q-OYXAL-BMNQF-DMF67',
        success(e) {
          console.log("=============",e.data)
          let data = e.data;
          if (data.status == 0) {
            //  console.log(data.message, data)
            res(data.result);
          } else {
            res({})
            wx.showToast({
              title: '腾讯位置服务异常，原因如下' + data.message,
              icon: "none"
            })
          }
        },
        fail() {
          res({})
          wx.showToast({
            title: '腾讯位置服务失败，请联系管理员',
            icon: "none"
          })
        }
      })
    });

  },

  // 跳转帮助文档
  goHelp() {
    wx.navigateTo({
      url: "/packageA/help/help"
    });
  },
  // 获取手机号码
  async bindgetphonenumber(e) {
    let user = wx.getStorageSync('userInfo');
    let result = await this.getLocation();
    console.log(result)
    let data = {
      userId: user.id,
      code:e.detail.code,
      province: result.ad_info.province,
      city: result.ad_info.city
    };
    let res = await userGetPhone(data);
    this.getUserDetail();
  },
  // 跳转信息填写
  goInfo() {
    let vm = this;
    wx.navigateTo({
      url: '/pages/personalCenter/info/info',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          vm.getUserDetail();
        },
      },
    })
  },
  async getUserDetail() {
    let user = wx.getStorageSync('userInfo');
    let res = await userDetail({
      id: user.id
    });
    this.setData({
      user: res
    })
  },
  async getIsPay() {  
    let res = await isPay();
    this.setData({
        payCheck: res
    })
  },
  go: function (e) {
    let type = e.currentTarget.dataset.type;
    if (type === '0') {
      wx.navigateTo({
        url: '../shopSite/shopSite',
      })
    } else if (type === '1') {
      wx.navigateTo({
        url: '../integralDetail/integralDetail',
      })
    } else if (type === '2') {
      let status = e.currentTarget.dataset.status;
      wx.navigateTo({
        url: '../order/order?status=' + status,
      })
    }
  },
  // 去充值
  goRechargeAmount() {
    wx.navigateTo({
      url: '/pages/personalCenter/rechargeAmount/rechargeAmount'
    })
  },

  // 打开二维码
  openCode: async function () {
    let user = wx.getStorageSync('userInfo');
    let data = {
      userId: user.id,
      code: wx.getStorageSync('token')
    };
    let res = await getQrCode(data);
    console.log(res)
    this.setData({
      codeUrl: res,
      visible: true,
    });
  },
  // 去提现
  withdraw(){
      wx.navigateTo({
        url: "/packageA/withdraw/withdraw",
      })
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  // 保存图片
  saveImage() {
    wx.showLoading({
      title: '加载中...'
    });
    //wx.downloadFile方法：下载文件资源到本地
    wx.downloadFile({
      // url: this.data.imgUrl, //图片地址
      url: this.data.codeUrl, //图片地址
      success: function (res) {
        //wx.saveImageToPhotosAlbum方法：保存图片到系统相册
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath, //图片文件路径
          success: function (data) {
            wx.hideLoading(); //隐藏 loading 提示框
            wx.showModal({
              title: '提示',
              content: '保存成功',
              modalType: false,
            })
          },
          // 接口调用失败的回调函数
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                modalType: false,
                success: modalSuccess => {
                  wx.openSetting({
                    success(settingdata) {
                      console.log("settingdata", settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次点击图片即可保存',
                          modalType: false,
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: '获取权限失败，将无法保存到相册哦~',
                          modalType: false,
                        })
                      }
                    },
                    fail(failData) {
                      console.log("failData", failData)
                    },
                    complete(finishData) {
                      console.log("finishData", finishData)
                    }
                  })
                }
              })
            }
          },
          complete(res) {
            wx.hideLoading(); //隐藏 loading 提示框
          }
        })
      }
    })


  },
})